package com.flea.repository.jdbc;

import com.flea.model.Product;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hc24
 * @date 2021.3.1 15:24
 */
public class ProductComplexRepositoryImpl extends BaseRepository<Product> implements ProductComplexRepository {
    @Override
    public Page<Product> findByCondition(Integer userId, String key, Integer minPrice, Pageable pageable) {
        // todo 根据动态条件查询Product
        StringBuilder sql = new StringBuilder();
        sql.append("select * from product where 1=1");
        List<Object> params = new ArrayList<>();
        if (userId != null) {
            params.add(userId);
            sql.append(" and user_id=?");
        }
        if (StringUtils.hasText(key)) {
            key = "%" + key + "%";
            params.add(key);
            params.add(key);
            sql.append(" and (name like ? or desc like ?)");
        }
        if (minPrice != null) {
            params.add(minPrice);
            sql.append(" and current_price<=?");
        }
        return findPage(sql.toString(), params, pageable, Product.class);
    }
}
